package com.souku.finance.application.base;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.souku.finance.application.R;
import com.souku.finance.application.utils.level.LogUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.utils.FileUtils;

/**
 * Created by Android on 16/11/25.
 */

public class BasePictureActivity extends BaseTitleBarActivity {

    private static final int REQUEST_IMAGE = 2;
    private static final int REQUEST_CAMERA = 100;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;

    private ArrayList<String> mSelectPath;
    private File mTmpFile;
    boolean showCamera = true;
    int maxNum = 9;

//    public void showOptionPopup(View rooView){
//        easeOptionPopup = new EaseOptionPopup(this);
//        easeOptionPopup.showAtLocation(rooView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        easeOptionPopup.setOnItemCilckListener(new EaseOptionPopup.OnItemCilckListener() {
//            @Override
//            public void onShoot(View view) {
//                launchCamera();
//                easeOptionPopup.dismiss();
//            }
//
//            @Override
//            public void onPicture(View view) {
//                pickImage();
//                easeOptionPopup.dismiss();
//            }
//
//            @Override
//            public void onCancel(View view) {
//                easeOptionPopup.dismiss();
//            }
//        });
//    }

    public void launchCamera() {
        showCameraAction();
    }

    private void showCameraAction() {
        if (ContextCompat.checkSelfPermission(BasePictureActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    getString(me.nereo.multi_image_selector.R.string.mis_permission_rationale_write_storage),
                    REQUEST_STORAGE_WRITE_ACCESS_PERMISSION);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(BasePictureActivity.this.getPackageManager()) != null) {
                try {
                    mTmpFile = FileUtils.createTmpFile(BasePictureActivity.this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (mTmpFile != null && mTmpFile.exists()) {
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mTmpFile));
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else {
                    Toast.makeText(BasePictureActivity.this, me.nereo.multi_image_selector.R.string.mis_error_image_not_exist, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(BasePictureActivity.this, me.nereo.multi_image_selector.R.string.mis_msg_no_camera, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            MultiImageSelector selector = MultiImageSelector.create(BasePictureActivity.this);
            selector.showCamera(showCamera);
            selector.count(maxNum);
            selector.single();
//          selector.multi();
            selector.origin(mSelectPath);
            selector.start(BasePictureActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(BasePictureActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                if (mSelectPath.size() == 1) {
                    onActivitySingleImage(mSelectPath.get(0));
                }
            }
        } else if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                if (mTmpFile != null) {
                    String absolutePath = mTmpFile.getAbsolutePath();
                    onActivitySingleImage(absolutePath);
                }
            } else {
                // delete tmp file
                while (mTmpFile != null && mTmpFile.exists()) {
                    boolean success = mTmpFile.delete();
                    if (success) {
                        mTmpFile = null;
                    }
                }
            }
        }
    }

    protected void onActivitySingleImage(String path) {
        LogUtils.e(path);
    }

    @Override
    public void internet() {

    }
}
